{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": [],
      "gpuType": "T4",
      "authorship_tag": "ABX9TyPMVWfftf8OvHN6BWqQwq5N",
      "include_colab_link": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/sugarforever/LangChain-Tutorials/blob/main/LangChain_TextSplitter.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "In this notebook, I will show you the main text splitters LangChain framework supports."
      ],
      "metadata": {
        "id": "amP-lCFgKUb-"
      }
    },
    {
      "cell_type": "code",
      "execution_count": 92,
      "metadata": {
        "id": "TO7WJgpwKLA-"
      },
      "outputs": [],
      "source": [
        "!pip install -qU langchain"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "long_text = '''\n",
        "WASHINGTON (Reuters) -Former U.S. President Donald Trump faces 37 criminal counts including charges of unauthorized retention of classified documents and conspiracy to obstruct justice after leaving the White House in 2021, according to federal court documents made public on Friday.\n",
        "\n",
        "The Justice Department made the charging documents public on a tumultuous day in which two of Trump's lawyers quit the case and a former aide face charges as well.\n",
        "\n",
        "The charges stem from Trump's treatment of sensitive government materials he took with him when he left the White House in January 2021.\n",
        "\n",
        "He is due to make a first court appearance in the case in a Miami court on Tuesday, a day before his 77th birthday.\n",
        "\n",
        "The indictment of a former U.S. president on federal charges is unprecedented in American history and emerges at a time when Trump is the front-runner for the Republican presidential nomination next year.\n",
        "\n",
        "Investigators seized roughly 13,000 documents from Trump's Mar-a-Lago estate in Palm Beach, Florida, nearly a year ago. One hundred were marked as classified, even though one of Trump's lawyers had previously said all records with classified markings had been returned to the government.\n",
        "'''"
      ],
      "metadata": {
        "id": "vwX4O06HUSye"
      },
      "execution_count": 93,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# CharacterTextSplitter"
      ],
      "metadata": {
        "id": "CAO_cdXlJwf-"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from langchain.text_splitter import CharacterTextSplitter"
      ],
      "metadata": {
        "id": "ISg0Zv8yKfVi"
      },
      "execution_count": 94,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "text_splitter = CharacterTextSplitter(        \n",
        "    separator = \"\\n\\n\",\n",
        "    chunk_size = 50,\n",
        "    chunk_overlap  = 10,\n",
        "    length_function = len,\n",
        ")\n",
        "\n",
        "documents = text_splitter.create_documents([long_text])\n",
        "print(documents[0].page_content)\n",
        "print(documents[1].page_content)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "VciFcr6sUr94",
        "outputId": "3482f157-47db-4f9c-df46-bbe0de490218"
      },
      "execution_count": 95,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "WARNING:langchain.text_splitter:Created a chunk of size 284, which is longer than the specified 50\n",
            "WARNING:langchain.text_splitter:Created a chunk of size 163, which is longer than the specified 50\n",
            "WARNING:langchain.text_splitter:Created a chunk of size 136, which is longer than the specified 50\n",
            "WARNING:langchain.text_splitter:Created a chunk of size 115, which is longer than the specified 50\n",
            "WARNING:langchain.text_splitter:Created a chunk of size 204, which is longer than the specified 50\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "WASHINGTON (Reuters) -Former U.S. President Donald Trump faces 37 criminal counts including charges of unauthorized retention of classified documents and conspiracy to obstruct justice after leaving the White House in 2021, according to federal court documents made public on Friday.\n",
            "The Justice Department made the charging documents public on a tumultuous day in which two of Trump's lawyers quit the case and a former aide face charges as well.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# RecursiveCharacterTextSplitter"
      ],
      "metadata": {
        "id": "zw2Wh3u_J0EV"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from langchain.text_splitter import RecursiveCharacterTextSplitter"
      ],
      "metadata": {
        "id": "i6dJm78aC6C_"
      },
      "execution_count": 96,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "text_splitter = RecursiveCharacterTextSplitter(\n",
        "    chunk_size = 50,\n",
        "    chunk_overlap  = 10,\n",
        "    length_function = len,\n",
        "    add_start_index = True\n",
        ")\n",
        "\n",
        "documents = text_splitter.create_documents([long_text])\n",
        "print(documents[0])\n",
        "print(documents[1])\n",
        "print(len(documents[1].page_content))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "Ep6YoDaXC9rM",
        "outputId": "427eaf1f-a5a4-4b98-b157-27a9099a5fa3"
      },
      "execution_count": 97,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "page_content='WASHINGTON (Reuters) -Former U.S. President' metadata={'start_index': 1}\n",
            "page_content='President Donald Trump faces 37 criminal counts' metadata={'start_index': 35}\n",
            "47\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# TokenTextSplitter"
      ],
      "metadata": {
        "id": "o5k-2CspJ4kP"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install tiktoken"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "rGeK2Vv6FRyr",
        "outputId": "3b7e9887-1b5a-416a-f8e4-a4748072cb41"
      },
      "execution_count": 98,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n",
            "Requirement already satisfied: tiktoken in /usr/local/lib/python3.10/dist-packages (0.4.0)\n",
            "Requirement already satisfied: regex>=2022.1.18 in /usr/local/lib/python3.10/dist-packages (from tiktoken) (2022.10.31)\n",
            "Requirement already satisfied: requests>=2.26.0 in /usr/local/lib/python3.10/dist-packages (from tiktoken) (2.27.1)\n",
            "Requirement already satisfied: urllib3<1.27,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests>=2.26.0->tiktoken) (1.26.15)\n",
            "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests>=2.26.0->tiktoken) (2022.12.7)\n",
            "Requirement already satisfied: charset-normalizer~=2.0.0 in /usr/local/lib/python3.10/dist-packages (from requests>=2.26.0->tiktoken) (2.0.12)\n",
            "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests>=2.26.0->tiktoken) (3.4)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from langchain.text_splitter import TokenTextSplitter"
      ],
      "metadata": {
        "id": "q9lZ0lfLFUZG"
      },
      "execution_count": 99,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "text_splitter = TokenTextSplitter(chunk_size=50, chunk_overlap=0)"
      ],
      "metadata": {
        "id": "ARvJa2NZFNhf"
      },
      "execution_count": 100,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "documents = text_splitter.create_documents([long_text])\n",
        "print(documents[0])"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "0iucjqxDFYSC",
        "outputId": "83845a19-8811-4865-8340-a9d7d512afb2"
      },
      "execution_count": 101,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "page_content='\\nWASHINGTON (Reuters) -Former U.S. President Donald Trump faces 37 criminal counts including charges of unauthorized retention of classified documents and conspiracy to obstruct justice after leaving the White House in 2021, according to federal court documents made public on Friday.\\n' metadata={}\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(documents[1])"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "KvIK0pgdYO00",
        "outputId": "a73fcf64-c70d-44e3-b670-d6e5a61baf5a"
      },
      "execution_count": 102,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "page_content=\"\\nThe Justice Department made the charging documents public on a tumultuous day in which two of Trump's lawyers quit the case and a former aide face charges as well.\\n\\nThe charges stem from Trump's treatment of sensitive government materials he took with him when\" metadata={}\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import tiktoken\n",
        "enc = tiktoken.get_encoding(\"gpt2\")\n",
        "print(len(enc.encode(documents[0].page_content)))\n",
        "print(len(enc.encode(documents[1].page_content)))\n",
        "print(len(enc.encode(documents[2].page_content)))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "413dzpLfFymc",
        "outputId": "bff7c8bc-e3db-4a7b-8a1e-ce7058fd6e1e"
      },
      "execution_count": 103,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "50\n",
            "50\n",
            "50\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(enc.encode(documents[0].page_content))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "ZRGx3pdWZJuh",
        "outputId": "db790f9c-430b-472a-a95c-6c14943787ae"
      },
      "execution_count": 104,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "[198, 21793, 357, 12637, 8, 532, 14282, 471, 13, 50, 13, 1992, 3759, 1301, 6698, 5214, 4301, 9853, 1390, 4530, 286, 22959, 21545, 286, 10090, 4963, 290, 10086, 284, 26520, 5316, 706, 4305, 262, 2635, 2097, 287, 33448, 11, 1864, 284, 2717, 2184, 4963, 925, 1171, 319, 3217, 13, 198]\n"
          ]
        }
      ]
    }
  ]
}